// require('babel-polyfill')
var commonUtil = require('./utils/common.js');
var isServer = typeof window === 'undefined';
var request = require('./utils/request.js');
var Paths = require('./utils/paths.js');

var redirectServer = function(context) {
  var res = context.res || null;
  var isPc = context.isPc || null;
  var params = commonUtil.filterParams(context);
  var str = '';
  for (var i in params) {
    str += i + '=' + params[i] + '&'
  }
  str = str.substr(0,str.length - 1)
   if(!res){
     var msg = '请提供res对象';
     return Promise.reject(msg)
   }
  if (isPc) {
    res.redirect('https://www.huize.com/apps/cps/index/clogin?'+str);
  } else {
    res.redirect('http://m.huize.com/apps/cps/index/cps/clogin?'+str);
  }
};

var costumerLogin = function (data) {
  return new Promise(function (resolve, reject) {
    var obj = {};
    if (!data) {
      obj = { success: false, msg: '必要的参数未提供' }
      resolve(obj);
      return;
    }
    var newData = commonUtil.filterParams(data,['backUrl','domain','source'])
    request.post(Paths.checkLogin, newData).then(function (res) {
      if (res.success) {
        if (res.data && res.data.hasUidLogin) {
          resolve(res)
        } else {
          if (isServer) {
            return redirectServer(data);
          } else {
            var showLoginModal = require('./utils/showLoginModal');
            showLoginModal(resolve, reject, data);
          }
        }
      } else {
        reject('login error')
      }
    })

  });
};
module.exports = {
    costumerLogin: costumerLogin,
    getSmsCode: commonUtil.getSmsCode,
    getLogin: commonUtil.getLogin
};
